package com.ybxx.dashboard.service.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.ybxx.core.command.QueryFilter;
import com.ybxx.core.dao.GenericDao;
import com.ybxx.core.service.impl.BaseServiceImpl;
import com.ybxx.core.util.DateUtil;
import com.ybxx.core.util.UUIDGenerator;
import com.ybxx.core.web.paging.PagingBean;
import com.ybxx.dashboard.dao.WatermeterDao;
import com.ybxx.dashboard.dao.WatermeterReadDao;
import com.ybxx.dashboard.model.Anmeter;
import com.ybxx.dashboard.model.AnmeterRead;
import com.ybxx.dashboard.model.CopyFormVO;
import com.ybxx.dashboard.model.ReadFormVO;
import com.ybxx.dashboard.model.Watermeter;
import com.ybxx.dashboard.model.WatermeterRead;
import com.ybxx.dashboard.service.WatermeterService;

public class WatermeterServiceImpl extends BaseServiceImpl<Watermeter>
		implements WatermeterService {
	private WatermeterDao watermeterDao;
	private WatermeterReadDao readDao;
	public WatermeterServiceImpl(WatermeterDao dao,WatermeterReadDao readDao) {
		super(dao);
		this.watermeterDao=dao;
		this.readDao=readDao;
		// TODO Auto-generated constructor stub
	}
	/*查询水表读数*/
	public List<ReadFormVO> queryReadForm(String printtype,String sorttype,String personid,String unitid,String ymonth){
		/*检查条件*/
		String printcondition="";
		String personcondition="";
		String unitcondition="";
		printcondition="order by a.snum asc";//按照表号排序
		if(unitid!=null && StringUtils.isNotEmpty(unitid)){
			String[] ids=unitid.split(",");
			String u_str="";
			String b_str="";
			String c_str="";
			for(int i=0;i<ids.length;i++){
				if(ids[i].indexOf("C")==0){
					c_str+="'"+ids[i].substring(1)+"',";
				}
				if(ids[i].indexOf("B")==0){
					b_str+="'"+ids[i].substring(1)+"',";
				}
				if(ids[i].indexOf("U")==0){
					u_str+="'"+ids[i].substring(1)+"',";
				}
			}
			if(StringUtils.isNotEmpty(u_str)){
				unitcondition+=" and u.uid in ("+u_str.substring(0,u_str.length()-1)+")";
			}
			if(StringUtils.isNotEmpty(b_str)){
				unitcondition+=" and b.bid in ("+b_str.substring(0,b_str.length()-1)+")";
			}
			if(StringUtils.isNotEmpty(c_str)){
				unitcondition+=" and c.cid in ("+c_str.substring(0,c_str.length()-1)+")";
			}
		}
		String sql="select a.acode,a.snum,a.roomcode,a.rid,a.compare,a.tel," +
				"case when b.ymonth is null then a.`start` when b.ymonth='"+ymonth+"' then b.thereadings else b.currentreading end thereadings," +
				"case when b.ymonth is null then '' when b.ymonth='"+ymonth+"' then b.currentreading else ''  end  currentreading," +
				"a.pid,a.cbname," +
				"case when b.ymonth is null then '' when b.ymonth='"+ymonth+"' then b.walkquantity else '' end walkquantity," +
				"case when b.ymonth is null then '' when b.ymonth='"+ymonth+"' then b.amount else '' end amount," +
				"case when b.ymonth is null then '' when b.ymonth='"+ymonth+"' then b.charge else '' end charge," +
				"case when b.ymonth is null then '0' when b.ymonth='"+ymonth+"' then b.state else '0' end state," +
				"case when b.ymonth is null then '' when b.ymonth='"+ymonth+"' then b.wmrcode else '' end amrcode " +
				"from " +
				"(select an.snum,an.wmcode acode,an.`start`,anr.roomcode,anr.rid,anr.compare,r.tel,rp.pid,rp.pname as cbname " +
				"from tbl_dashboard_watermeter an,tbl_dashboard_wartermeter_room anr,tbl_base_residents r,tbl_base_read_person rp, " +
				"tbl_base_room room,tbl_base_unit u,tbl_base_ban b,tbl_base_community c "+
				"where an.wmcode=anr.wmcode and anr.rid=r.rid and rp.pid=an.pid " +
				"and anr.rid=room.rid and room.uid=u.uid and u.bid=b.bid and b.cid=c.cid"+personcondition+unitcondition+
				") a left join " +
				"(select arm.* from tbl_dashboard_watermeter_read arm," +
				"(select max(ymonth) ymonth,wmcode from tbl_dashboard_watermeter_read " +
				"where ymonth in ('"+ymonth+"','"+DateUtil.addMonthFormDate(ymonth+"-01",-1)+"') group by wmcode )tmp " +
				"where arm.ymonth=tmp.ymonth and arm.wmcode=tmp.wmcode) b " +
				"on a.acode=b.wmcode and a.rid=b.rid " +printcondition;
		return watermeterDao.queryReadForm(sql,printtype);
	}
	/*查询水表抄表单*/
	public Map<String,List<CopyFormVO>> queryCopyForm(String printtype,String sorttype,String personid,String unitid){
		/*检查条件*/
		String printcondition="";
		String sortcondition="";
		String personcondition="";
		String unitcondition="";
		if(printtype==null || "".equals(printtype) || "unit".equals(printtype)){
			printcondition="order by substring_index(substring_index(a.roomcode,'(',-1),')',1)";
		}else{
			printcondition="order by a.pid";
		}
		if(sorttype==null || "".equals(sorttype) || "meter".equals(sorttype)){
			sortcondition=",a.snum asc";
		}else{
			sortcondition=",a.roomcode";
		}
		if(personid!=null && StringUtils.isNotEmpty(personid)){
			String[] ids=personid.split(",");
			String str="";
			for(int i=0;i<ids.length;i++){
				str+="'"+ids[i]+"',";
			}
			personcondition=" and rp.pid in ("+str.substring(0,str.length()-1)+")";
		}
		if(unitid!=null && StringUtils.isNotEmpty(unitid)){
			String[] ids=unitid.split(",");
			String u_str="";
			String b_str="";
			String c_str="";
			for(int i=0;i<ids.length;i++){
				if(ids[i].indexOf("C")==0){
					c_str+="'"+ids[i].substring(1)+"',";
				}
				if(ids[i].indexOf("B")==0){
					b_str+="'"+ids[i].substring(1)+"',";
				}
				if(ids[i].indexOf("U")==0){
					u_str+="'"+ids[i].substring(1)+"',";
				}
			}
			if(StringUtils.isNotEmpty(u_str)){
				unitcondition+=" and u.uid in ("+u_str.substring(0,u_str.length()-1)+")";
			}
			if(StringUtils.isNotEmpty(b_str)){
				unitcondition+=" and b.bid in ("+b_str.substring(0,b_str.length()-1)+")";
			}
			if(StringUtils.isNotEmpty(c_str)){
				unitcondition+=" and c.cid in ("+c_str.substring(0,c_str.length()-1)+")";
			}
		}
		String sql="select a.pname,a.snum,a.roomcode,a.tel," +
				"case when b.currentreading is null then a.`start` else b.currentreading end thereadings," +
				"'' currentreading,a.pid,a.cbname " +
				"from " +
				"(select an.snum,an.wmcode as acode,an.`start`,anr.roomcode,anr.pname,r.tel,rp.pid,rp.pname as cbname " +
				"from tbl_dashboard_watermeter an,tbl_dashboard_wartermeter_room anr,tbl_base_residents r,tbl_base_read_person rp, " +
				"tbl_base_room room,tbl_base_unit u,tbl_base_ban b,tbl_base_community c "+
				"where an.wmcode=anr.wmcode and anr.rid=r.rid and rp.pid=an.pid " +
				"and anr.rid=room.rid and room.uid=u.uid and u.bid=b.bid and b.cid=c.cid"+personcondition+unitcondition+
				") a left join " +
				"(select * from tbl_dashboard_watermeter_read group by wmcode HAVING max(ymonth)) b " +
				"on a.acode=b.wmcode " +printcondition+sortcondition;
		return watermeterDao.queryCopyForm(sql,printtype);
	}
	@Override
	public Watermeter save(Watermeter entity) {
		watermeterDao.excuteSql("delete from tbl_dashboard_wartermeter_room where wmcode='"+entity.getWmcode()+"'");
		return super.save(entity);
	}

	/*查询分页数据*/
	public List<Watermeter> queryPage(QueryFilter filter,String cid,String bid,String uid,String rid){
		String hql="from Watermeter a left join fetch a.spread s left join fetch a.readPerson r" +
				"left join fetch a.watermeterRooms ar where 1=1";
		if(cid!=null && !"".equals(cid)){
			hql=hql+" and ar.room.unit.ban.community.cid='"+cid+"'";
		}
		if(bid!=null && !"".equals(bid)){
			hql=hql+" and ar.room.unit.ban.bid='"+bid+"'";
		}
		if(uid!=null && !"".equals(uid)){
			hql=hql+" and ar.room.unit.uid='"+uid+"'";
		}
		if(rid!=null && !"".equals(rid)){
			hql=hql+" and ar.room.rid='"+rid+"'";
		}
		String counthql=hql;
		hql=hql+" order by a.snum";
		int rows=watermeterDao.findCountByHql(counthql+" group by a.wmcode", null);
		List<Watermeter> watermeters= watermeterDao.findByHql(hql, null, filter.getPagingBean());
		filter.getPagingBean().setTotalItems(rows);
		return watermeters;
	}

	public Watermeter load(String wmcode) {
		String hql="from Watermeter a left join fetch a.spread s left join fetch a.readPerson r" +
		"left join fetch a.watermeterRooms ar left join fetch ar.room ro left join fetch ar.residents res where a.wmcode='"+wmcode+"'";
		return (Watermeter)watermeterDao.findUnique(hql, null);
	}
	public void saveRead(String ctime, String ymonth, List<ReadFormVO> vos,String loginid) {
		for(Iterator<ReadFormVO> iter=vos.iterator();iter.hasNext();){
			ReadFormVO vo=iter.next();
			String[] rids=vo.getRids().split(",");
			String[] compares=vo.getCompares().split(",");
			String[] amrcodes=(vo.getAmrcodes()==null || vo.getAmrcodes().equals(""))?null:vo.getAmrcodes().split(",");
			if("0".equals(vo.getState())){
				for(int i=0;i<rids.length;i++){
					WatermeterRead read=new WatermeterRead();
					read.setWmrcode((amrcodes==null || amrcodes.length<=i)?UUIDGenerator.getUUID():amrcodes[i]);
					read.setWmcode(vo.getCode());
					read.setRid(rids[i]);
					read.setCompare(compares[i]);
					read.setThereadings(vo.getThereadings());
					read.setCurrentreading(vo.getCurrentreading());
					read.setYmonth(ymonth);
					read.setCtime(ctime);
					read.setWalkquantity(vo.getWalkquantity());
					read.setAmount(vo.getAmount());
					read.setCharge(vo.getCharge());
					read.setActual((Float.parseFloat(compares[i])*Float.parseFloat(vo.getCharge()))+"");
					read.setRtime(DateUtil.formatDate(new Date()));
					read.setOperid(loginid);
					read.setState("0");
					readDao.save(read);
				}
			}
			
		}
		
	}
}
